package com.sec.samsung.android.app.baymax.view.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Filter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sec.samsung.android.app.baymax.R;
import com.sec.samsung.android.app.baymax.controll.BaymaxRequestManager;
import com.sec.samsung.android.app.baymax.controll.IRequestListener;
import com.sec.samsung.android.app.baymax.model.Symptom;
import com.sec.samsung.android.app.baymax.model.reponse.ResponseListSymptomsData;
import com.sec.samsung.android.app.baymax.utils.BaymaxConstant;
import com.sec.samsung.android.app.baymax.utils.StringUtility;
import com.sec.samsung.android.app.baymax.view.adapter.ListSymptomAdapter;
import com.sec.samsung.android.app.baymax.view.adapter.ListSymptomAdapter.OnCheckItemListener;

public class BaseSymptomQuestion extends Activity implements OnCheckItemListener {
    private static final int ADDRESS_TRESHOLD = 1;
    private Button mBtnBack;
    private LinearLayout mLayoutLoading;
    private LinearLayout mLayoutNoConnection;
    private AutoCompleteTextView mTxtSymtomSearch;
    private ListView mListSymptoms;
    private LinearLayout mBtnNext;

    private LinearLayout mLayoutSymtoms;
    private ListSymptomAdapter mListSymptomAdapter;
    private Filter filter;
    private ArrayAdapter<String> adapter;

    private ArrayList<Symptom> mListDataSymptoms = new ArrayList<Symptom>();
    private ArrayList<Symptom> mListSearchSymptoms = new ArrayList<Symptom>();

    private ArrayList<Boolean> mListCheckDataSymptoms = new ArrayList<Boolean>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_symptom);

        initLayout();

        initData();
    }

    private void initData() {
        String bodyType = getIntent().getExtras().getString("body_part");
        BaymaxRequestManager.getInstance(this).getSymptonSuggestByType(bodyType, new IRequestListener() {

            @Override
            public void onResponse(String response) {
                if (StringUtility.isEmpty(response))
                    return;
                Gson gson = new GsonBuilder().serializeNulls().create();
                ResponseListSymptomsData responseData = gson.fromJson(response, ResponseListSymptomsData.class);
                if (responseData == null || !BaymaxConstant.SUCCESS.equals(responseData.message))
                    return;
                mListDataSymptoms = responseData.value;
                int size = mListDataSymptoms.size();
                if (size > 4) {
                    for (int i = 3; i < mListDataSymptoms.size(); i++)
                        mListDataSymptoms.remove(i);
                    size = 4;
                }

                for (int i = 0; i < size; i++)
                    mListCheckDataSymptoms.add(false);
                mListSymptomAdapter.addSymptoms(mListDataSymptoms);
            }

            @Override
            public void onErrorResponse(String errorMessage) {
                mLayoutSymtoms.setVisibility(View.GONE);
                mLayoutNoConnection.setVisibility(View.VISIBLE);
            }
        }, this);

        filter = new Filter() {
            @Override
            protected void publishResults(CharSequence constraint,
                    FilterResults results) {
                mTxtSymtomSearch.setAdapter(adapter);
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                if (constraint != null && (constraint.length() > ADDRESS_TRESHOLD)) {
                    Log.i("Filter", "doing a search ..:" + constraint);
                    searchTextFromServer(constraint);
                }
                return null;
            }
        };

        adapter = new ArrayAdapter<String>(this, R.layout.my_custom_dropdown) {
            public android.widget.Filter getFilter() {
                return filter;
            }
        };

       mTxtSymtomSearch.setAdapter(adapter);
    }

    private void searchTextFromServer(CharSequence constraint) {
        BaymaxRequestManager.getInstance(this).getTextBySearchingSymptoms(String.valueOf(constraint), new IRequestListener() {

            @Override
            public void onResponse(String response) {
                Log.d("KieuThang", "searchTextFromServer:onResponse:" + response);
                if (StringUtility.isEmpty(response))
                    return;
                Gson gson = new GsonBuilder().serializeNulls().create();
                ResponseListSymptomsData responseData = gson.fromJson(response, ResponseListSymptomsData.class);
                if (responseData == null || !BaymaxConstant.SUCCESS.equals(responseData.message))
                    return;
                mListSearchSymptoms = responseData.value;
                String[] symtoms = new String[mListSearchSymptoms.size()];
                for (int i = 0; i < mListSearchSymptoms.size(); i++) {
                    symtoms[i] = mListSearchSymptoms.get(i).getSymptom();
                }
                Log.d("KieuThang", "symtoms:" + symtoms.length);
                adapter = new ArrayAdapter<String>(BaseSymptomQuestion.this, R.layout.my_custom_dropdown, symtoms);
                //mTxtSymtomSearch.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onErrorResponse(String errorMessage) {
                Log.d("KieuThang", "searchTextFromServer:onErrorResponse:" + errorMessage);
            }
        }, this);
    }

    private void initLayout() {
        mBtnBack = (Button) findViewById(R.id.btn_back);
        mBtnNext = (LinearLayout) findViewById(R.id.layout_next);
        mLayoutLoading = (LinearLayout) findViewById(R.id.layout_loading);
        mLayoutNoConnection = (LinearLayout) findViewById(R.id.layout_no_connection);
        mTxtSymtomSearch = (AutoCompleteTextView) findViewById(R.id.txt_symptoms_search);
        mListSymptoms = (ListView) findViewById(R.id.list_your_symptoms);
        mListSymptomAdapter = new ListSymptomAdapter(this, mListDataSymptoms);

        mListSymptomAdapter.setLisntener(this);
        mListSymptoms.setAdapter(mListSymptomAdapter);

        mTxtSymtomSearch.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (!mListSymptomAdapter.containsSymptom(mListSearchSymptoms.get(position)) && !mListDataSymptoms.contains(mListSearchSymptoms.get(position))) {
                    mListSymptomAdapter.addSymptom(mListSearchSymptoms.get(position));
                    mListCheckDataSymptoms.add(false);
                }
                mTxtSymtomSearch.setText("");
            }
        });
        mBtnBack.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mBtnNext.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                onClickNextButton();
            }
        });
    }

    private void onClickNextButton() {
        ArrayList<String> listSymtomIds = new ArrayList<String>();
        for (int i = 0; i < mListCheckDataSymptoms.size(); i++) {
            if (mListCheckDataSymptoms.get(i) == true) {
                listSymtomIds.add(mListDataSymptoms.get(i).getSymptomId());
                Log.d("KieuThang", "mListCheckDataSymptoms.get(i) == true=>" + i);
            }
        }
        if (listSymtomIds.size() == 0) {
            Toast.makeText(this, "Please choose a base symtoms", Toast.LENGTH_SHORT).show();
        } else {

            BaymaxRequestManager.getInstance(this).postListBaseSymptoms(listSymtomIds, new IRequestListener() {

                @Override
                public void onResponse(String response) {
                    Log.d("KieuThang", "postListBaseSymptoms:onResponse=>" + response);
                    Intent intent = new Intent(BaseSymptomQuestion.this, DetailSymptomQuestions.class);
                    intent.putExtra("symptoms_question", response);
                    startActivity(intent);
                }

                @Override
                public void onErrorResponse(String errorMessage) {
                    Log.d("KieuThang", "postListBaseSymptoms:errorMessage=>" + errorMessage);
                    mLayoutSymtoms.setVisibility(View.GONE);
                    mLayoutNoConnection.setVisibility(View.VISIBLE);
                }
            }, this);
        }
    }

    @Override
    public void onCheckItemLisntener(int position, boolean value) {
        if (position < mListCheckDataSymptoms.size())
            mListCheckDataSymptoms.set(position, value);
    }
}
